<template>
  <view class="bottle-container" :class="bottleTheme">
    <view class="bottle-content">
      <view class="svg-bottle-wrapper" :class="bottleScale" @touchstart="onTouchStart" @touchmove="onTouchMove" @touchend="onTouchEnd">
        <svg class="bottle-svg" viewBox="-76 0 292 292" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid meet">
          <defs>
            <linearGradient :id="'bottleGradient-' + bottleTheme" x1="0%" y1="0%" x2="0%" y2="100%">
              <stop offset="0%" :stop-color="getThemeColor('bottleTop')" />
              <stop offset="100%" :stop-color="getThemeColor('bottleBottom')" />
            </linearGradient>
            <linearGradient :id="'milkGradient-' + bottleTheme" x1="0%" y1="0%" x2="0%" y2="100%">
              <stop offset="0%" :stop-color="getThemeColor('milkTop')" />
              <stop offset="100%" :stop-color="getThemeColor('milkBottom')" />
            </linearGradient>
            <radialGradient :id="'highlightGradient-' + bottleTheme" cx="50%" cy="20%" r="80%">
              <stop offset="0%" stop-color="#fff" stop-opacity="0.7" />
              <stop offset="100%" stop-color="#fff" stop-opacity="0" />
            </radialGradient>
            <clipPath id="bottleClip">
              <path d="M16.257,281.456a28.754,28.754,0,0,1-12.648-17.82c-1.788-7.126-1.109-17.568-.5-31.019.835-18.431,3.947-79.695,4.527-93.677A43.578,43.578,0,0,1,10.9,124.505a25.89,25.89,0,0,1,5.664-8.6l.032-.028a28.34,28.34,0,0,0,7.61,2.365,272.855,272.855,0,0,0,45.4,3.4,272.233,272.233,0,0,0,45.749-3.459,23.016,23.016,0,0,0,8.171-2.3.3.3,0,0,1,.032.024,25.89,25.89,0,0,1,5.664,8.6,43.554,43.554,0,0,1,3.265,14.435c.58,13.982,3.692,75.246,4.527,93.677.609,13.451,1.288,23.893-.5,31.019-2.606,10.391-9.1,16.89-19.125,21.292-13.28,3.817-28.787,4.779-47.783,4.779-18.249,0-34.711-.962-46.224-4.5A44.77,44.77,0,0,1,16.257,281.456Z" />
            </clipPath>
          </defs>
          <!-- 奶液层 -->
          <path :d="milkWavePath" :fill="'url(#milkGradient-' + bottleTheme + ') '" clip-path="url(#bottleClip)" :style="animOn ? 'transition: d 0.5s cubic-bezier(.4,1.6,.4,1);' : ''" />
          <!-- 奶液波浪高光 -->
          <path :d="milkWaveHighlightPath" :fill="'url(#highlightGradient-' + bottleTheme + ') '" clip-path="url(#bottleClip)" :style="'pointer-events:none;'" />
          <!-- 奶瓶轮廓 -->
          <path class="a" d="M45.074,46.263a103.671,103.671,0,0,0-9.862,5.923c-8.244,5.894-14.28,14.585-9.875,27.821A274.584,274.584,0,0,0,69.6,83.226a275.573,275.573,0,0,0,44.268-3.212c4.4-13.241-1.632-21.933-9.877-27.828C95.482,46.1,84.69,42.911,83.987,36.72L83.946,18c-.008-3.7-.914-8.174-3.262-11.034C78.587,4.417,74.1,2.359,69.6,2.359S60.617,4.417,58.52,6.97C56.172,9.83,55.266,14.3,55.258,18L55.217,36.720C54.777,40.6,50.385,43.294,45.074,46.263Z" fill="none" :stroke="getThemeColor('bottleStroke')" stroke-width="4" />
          <path class="a" d="M16.257,281.456a28.754,28.754,0,0,1-12.648-17.82c-1.788-7.126-1.109-17.568-.5-31.019.835-18.431,3.947-79.695,4.527-93.677A43.578,43.578,0,0,1,10.9,124.505a25.89,25.89,0,0,1,5.664-8.6l.032-.028a28.34,28.34,0,0,0,7.61,2.365,272.855,272.855,0,0,0,45.4,3.4,272.233,272.233,0,0,0,45.749-3.459,23.016,23.016,0,0,0,8.171-2.3.3.3,0,0,1,.032.024,25.89,25.89,0,0,1,5.664,8.6,43.554,43.554,0,0,1,3.265,14.435c.58,13.982,3.692,75.246,4.527,93.677.609,13.451,1.288,23.893-.5,31.019-2.606,10.391-9.1,16.89-19.125,21.292-13.28,3.817-28.787,4.779-47.783,4.779-18.249,0-34.711-.962-46.224-4.5A44.77,44.77,0,0,1,16.257,281.456Z" fill="none" :stroke="getThemeColor('bottleStroke')" stroke-width="4" />
          <path class="c" d="M116.056,79.793q-.384-.021-.77-.015A272.409,272.409,0,0,1,69.6,83.226,270.53,270.53,0,0,1,24.07,79.785a11.85,11.85,0,0,0-8.707,4.6c-2.536,3.371-3.292,7.722-3.835,11.9a69.32,69.32,0,0,0-.829,10.972c-.053,2.419,2.538,6.516,4.089,7.556,2.709,1.817,5.437,2.631,9.418,3.429a272.868,272.868,0,0,0,45.4,3.4,272.233,272.233,0,0,0,45.749-3.459,21.633,21.633,0,0,0,9.981-3.371c1.55-1.04,4.141-5.137,4.088-7.556a69.32,69.32,0,0,0-.829-10.972c-.543-4.182-1.3-8.533-3.835-11.9A11.817,11.817,0,0,0,116.056,79.793Z" fill="none" :stroke="getThemeColor('bottleStroke')" stroke-width="4" />
          <!-- 刻度线 -->
          <g>
            <line v-for="mark in scaleMarks" :key="mark" :x1="115" :y1="getScaleY(mark)" :x2="125" :y2="getScaleY(mark)" :stroke="getThemeColor('scale')" stroke-width="2" opacity="0.8" />
            <text v-for="mark in scaleMarks" :key="'text-' + mark" :x="130" :y="getScaleY(mark) + 4" :fill="getThemeColor('scale')" font-size="11" font-family="Arial" opacity="0.9">{{ mark }}</text>
          </g>
          <!-- 投影 -->
          <ellipse cx="70" cy="290" rx="60" ry="10" :fill="getThemeColor('shadow')" opacity="0.18" />
        </svg>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'MilkBottle',
  props: {
    // 当前选择的奶量
    value: {
      type: Number,
      default: 120
    },
    // 最大奶量
    maxAmount: {
      type: Number,
      default: 240
    },
    // 最小奶量
    minAmount: {
      type: Number,
      default: 10
    },
    // 主题
    theme: {
      type: String,
      default: 'dark'
    }
  },
  data() {
    return {
      // 内部值，与props同步
      selectedAmount: this.value,
      
      // 奶瓶选择器相关数据
      touchStartY: 0,
      touchStartAmount: this.value,
      bottleTheme: this.theme,
      animOn: true,
      amountBounce: false,
      waveIntensity: 0,
      milkWavePath: '',
      milkWaveHighlightPath: '',
      
      // 奶瓶主题颜色
      themeColors: {
        dark: {
          bottleTop: '#444',
          bottleBottom: '#222',
          bottleStroke: '#fff',
          milkTop: '#fff',
          milkBottom: '#bbb',
          scale: '#fff',
          shadow: '#000'
        }
      },
      scaleMarks: [50, 100, 150, 200, 250],
      
      // 波浪动画相关变量
      isSliding: false,
      slideEndTimer: null,
      waveDecayTimer: null,
      waveTimer: null,
      bottleScale: 'scale-100' // 控制奶瓶缩放
    }
  },
  watch: {
    // 监听外部value变化
    value(newVal) {
      if (newVal !== this.selectedAmount) {
        this.selectedAmount = newVal;
        this.updateMilkWavePath();
      }
    }
  },
  mounted() {
    // 初始化奶瓶组件
    this.updateMilkWavePath();
    this.startWaveAnimation();
  },
  beforeDestroy() {
    this.clearAllTimers();
  },
  methods: {
    // 更新奶液波浪路径
    updateMilkWavePath() {
      try {
        const bottleHeight = 292
        const fillPercent = this.selectedAmount / this.maxAmount
        const fillHeight = Math.max(10, Math.min(220, fillPercent * 220))
        const waveY = 292 - fillHeight

        // 当波纹强度很低时，混合轻微波动和衰减波纹
        if (this.waveIntensity <= 0.1) {
          // 计算轻微波动
          const gentleAmp = 0.8 // 非常轻微的波浪幅度
          const gentleFreq = 1.5 // 较低的频率
          const step = 20 // 较大的步长，让波浪更平滑
          let d = `M-76,${waveY}`
          for (let x = -76; x <= 216; x += step) {
            const time = Date.now() / 8000 // 非常慢的滚动速度
            const gentleWaveY =
              waveY +
              Math.sin((x / 60 + time) * Math.PI * gentleFreq) * gentleAmp

            // 如果还有衰减波纹，则混合两种效果
            let finalWaveY = gentleWaveY
            if (this.waveIntensity > 0.01) {
              const decayTime = Date.now() / 2000
              const decayWaveY =
                waveY +
                Math.sin((x / 20 + decayTime) * Math.PI * 3) *
                  (3 * this.waveIntensity)
              // 平滑混合：衰减波纹逐渐减弱，轻微波动逐渐增强
              const mixRatio = this.waveIntensity / 0.1 // 0.01-0.1 映射到 0.1-1
              finalWaveY = gentleWaveY * (1 - mixRatio) + decayWaveY * mixRatio
            }

            d += ` Q${x + step / 2},${finalWaveY - gentleAmp / 3} ${
              x + step
            },${finalWaveY}`
          }
          d += ` V292 H-76 Z`
          this.milkWavePath = d
        } else {
          // 根据波纹强度调整波纹参数
          const baseAmp = 3 // 基础波纹幅度
          const amp = baseAmp * this.waveIntensity, // 根据强度调整幅度
            freq = 3, // 增加波纹频率
            step = 12 // 减小步长，让波纹更平滑
          let d = `M-76,${waveY}`
          for (let x = -76; x <= 216; x += step) {
            const time = Date.now() / 2000 // 加快滚动速度
            const waveY2 =
              waveY + Math.sin((x / 20 + time) * Math.PI * freq) * amp
            d += ` Q${x + step / 2},${waveY2 - amp / 2} ${x + step},${waveY2}`
          }
          d += ` V292 H-76 Z`
          this.milkWavePath = d
        }

        // 高光波浪，与主波纹略有不同的频率产生层次感
        const y = waveY - 2
        
        // 根据波纹强度决定高光波浪算法
        if (this.waveIntensity <= 0.1) {
          // 计算轻微高光波动
          const gentleAmp = 0.5 // 更轻微的高光波浪幅度
          const gentleFreq = 1.2 // 稍微不同的频率
          const step = 20 // 较大的步长，让波浪更平滑
          let d = `M-76,${y}`
          for (let x = -76; x <= 216; x += step) {
            const time = Date.now() / 9000 // 稍微不同的速度
            const gentleWaveY =
              y +
              Math.sin((x / 70 + time + 0.3) * Math.PI * gentleFreq) * gentleAmp

            // 如果还有衰减波纹，则混合两种效果
            let finalWaveY = gentleWaveY
            if (this.waveIntensity > 0.01) {
              const decayTime = Date.now() / 2500
              const decayWaveY =
                y +
                Math.sin((x / 25 + decayTime + 0.5) * Math.PI * 2.5) *
                  (2 * this.waveIntensity)
              // 平滑混合：衰减波纹逐渐减弱，轻微波动逐渐增强
              const mixRatio = this.waveIntensity / 0.1 // 0.01-0.1 映射到 0.1-1
              finalWaveY = gentleWaveY * (1 - mixRatio) + decayWaveY * mixRatio
            }

            d += ` Q${x + step / 2},${finalWaveY - gentleAmp / 3} ${
              x + step
            },${finalWaveY}`
          }
          d += ` V${y + 15} H-76 Z`
          this.milkWaveHighlightPath = d
        } else {
          // 根据波纹强度调整高光波纹参数
          const baseAmp = 2 // 基础高光波纹幅度
          const amp = baseAmp * this.waveIntensity,
            freq = 2.5,
            step = 12
          let d = `M-76,${y}`
          for (let x = -76; x <= 216; x += step) {
            const time = Date.now() / 2500 // 稍微不同的速度
            const waveY2 = y + Math.sin((x / 25 + time + 0.5) * Math.PI * freq) * amp
            d += ` Q${x + step / 2},${waveY2 - amp / 2} ${x + step},${waveY2}`
          }
          d += ` V${y + 15} H-76 Z`
          this.milkWaveHighlightPath = d
        }
      } catch (error) {
        console.error('更新波浪路径时发生错误:', error)
        // 设置默认的波浪路径
        this.milkWavePath = 'M-76,200 L216,200 V292 H-76 Z'
        this.milkWaveHighlightPath = 'M-76,198 L216,198 V215 H-76 Z'
      }
    },

    // 开始波浪动画
    startWaveAnimation() {
      this.clearTimer(this.waveTimer)
      this.waveTimer = setInterval(() => {
        this.updateMilkWavePath()
      }, 16) // 修改为16ms更新一次(60fps)，与实验室页面一致
    },

    // 开始波浪衰减
    startWaveDecay() {
      this.clearTimer(this.waveDecayTimer)
      this.waveDecayTimer = setInterval(() => {
        // 使用递减值的方式，与实验室页面一致
        if (this.waveIntensity > 0) {
          this.waveIntensity -= 0.008 // 每次减少0.008，大约125帧后完全平滑（约2秒）
          if (this.waveIntensity < 0) {
            this.waveIntensity = 0
          }
        } else {
          // 波纹完全消失，清理定时器
          this.clearTimer(this.waveDecayTimer)
          this.waveDecayTimer = null
        }
      }, 16) // 16ms一次，约60fps
    },

    // 清理所有定时器
    clearAllTimers() {
      this.clearTimer(this.waveTimer)
      this.clearTimer(this.slideEndTimer)
      this.clearTimer(this.waveDecayTimer)
    },

    // 清理单个定时器
    clearTimer(timer) {
      if (timer) {
        clearInterval(timer)
      }
    },

    // 计算刻度线位置
    getScaleY(mark) {
      const percent = (mark - this.minAmount) / (this.maxAmount - this.minAmount)
      const bottleBodyStart = 150
      const bottleBodyEnd = 270
      const bottleBodyHeight = bottleBodyEnd - bottleBodyStart
      return bottleBodyEnd - percent * bottleBodyHeight
    },

    // 触摸开始事件
    onTouchStart(e) {
      this.touchStartY = e.touches[0].clientY
      this.touchStartAmount = this.selectedAmount
      this.isSliding = true
      this.waveIntensity = 1
      this.clearTimer(this.slideEndTimer)
      this.clearTimer(this.waveDecayTimer)
    },

    // 触摸移动事件
    onTouchMove(e) {
      e.preventDefault()
      const deltaY = this.touchStartY - e.touches[0].clientY
      const deltaAmount = Math.round(deltaY * 0.5) // 修改为0.5系数，与实验室页面一致

      let newAmount = this.touchStartAmount + deltaAmount
      newAmount = Math.max(this.minAmount, Math.min(this.maxAmount, newAmount))
      newAmount = Math.round(newAmount / 5) * 5 // 按5的倍数取整，与实验室页面一致
      
      if (newAmount !== this.selectedAmount) {
        this.selectedAmount = newAmount
        // 向父组件发送更新事件
        this.$emit('input', this.selectedAmount)
        this.$emit('change', this.selectedAmount)
        
        // 固定波浪强度为1.0，与实验室页面一致
        this.waveIntensity = 1.0
      }
    },

    // 触摸结束事件
    onTouchEnd() {
      this.isSliding = false
      
      // 直接开始衰减，不需要延迟
      this.startWaveDecay()
      
      // 向父组件发送最终的值
      this.$emit('input', this.selectedAmount)
      this.$emit('change', this.selectedAmount)
      
      // 触发波浪动画
      this.amountBounce = true
      setTimeout(() => {
        this.amountBounce = false
      }, 300)
    },
    
    // 获取主题颜色
    getThemeColor(key) {
      return this.themeColors[this.bottleTheme][key]
    }
  }
}
</script>

<style scoped>
.bottle-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: visible;
  padding: 0;
}

.bottle-content {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  max-height: 100%;
}

.svg-bottle-wrapper {
  width: 80%; /* 增加宽度 */
  height: auto;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: transform 0.3s ease;
  margin-top: 20rpx; /* 增加顶部间距 */
}

.bottle-svg {
  width: 100%;
  height: auto;
  transform: scale(1.1); /* 适度放大 */
  max-height: 100%;
}

/* 奶瓶缩放动画 */
.scale-100 {
  transform: scale(1.1);
}
.scale-110 {
  transform: scale(1.15);
}
.scale-90 {
  transform: scale(1.05);
}

/* 动画效果 */
@keyframes bounce {
  0%, 100% {
    transform: scale(1.1);
  }
  50% {
    transform: scale(1.15);
  }
}

.bounce {
  animation: bounce 0.3s ease-in-out;
}
</style> 